/*
 * 数据库
 * */
const pg = require('pg');
//const MATH = require('math');
const constring = "tcp://postgres:763127186@localhost/postgres";
//初始化
exports.init = ()=> {return new userDB()}
const userTableName = 'HXUserTable';
class db {
	constructor() { 
	}
	all () {
		console.log("update beginning");
		var sql = "select * from " + userTableName;
		var query = this.client.query(sql);
		query.on('row', function(row) {
			console.log(JSON.stringify(row))
		});
	}
//	//删除表  删除表中的所有行，而不记录单个行删除操作。  参数 userTableName 是要截断的表的名称或要删除其全部行的表的名称
	truncate () {
		var sql = "TRUNCATE TABLE " + userTableName;
		var query = this.client.query(sql);
		query.on('row', function(row) {
			console.log(JSON.stringify(row))
		});
	}
	//	this.truncate();
	//删除表
	truncate1 () {
		var sql = "Delete from " + userTableName + " where 1=1";
		var query = this.client.query(sql);
		query.on('row', function(row) {
			console.log(JSON.stringify(row))
		});
	}
	//
	DROP () {
		var sql = "DROP TABLE " + userTableName;
		var query = this.client.query(sql);
		query.on('row', function(row) {
			console.log(JSON.stringify(row))
		});
	}
}
/*
 * 数据库对象
 * */
class userDB extends db {
	constructor() {
		super()
	    /*
		 * 管理sockt的数据 
		 * */
		this.socketDic = {};
		/*
		 * 离线消息缓存
		 * */
		this.chatCache = {};
		this.client = new pg.Client(constring); //数据库操作对象
		this.client.connect(); //连接数据库
		//创建用户数据库表
		this.client.query('CREATE TABLE IF NOT EXISTS ' + userTableName + ' (_id serial NOT NULL, user_id serial primary key, ' +
			'username varchar(10) unique, passwoed varchar(30),' +
			'nickname text, ' +
			'friends int[], ' +
			'token char(32))');
		
		super.all()
//		super.DROP ()//清空
	}
	/*
	 * 创建用户数据
	 * */
	foundUser (name, passwoed, nickname, callback, fdCallback) {
		const sql = "insert into " + userTableName + " (username, passwoed, nickname, friends) values('" + name + "', '" + passwoed + "','"+ nickname +"', '{}')"
		this.client.query(sql, (error, results)=>{
			if(error) {
				fdCallback && fdCallback();
				return console.error('error running query--', error);
			}
			callback && callback()
		});
	}
	
	
	
	
}


var dbdsa = function() {
	/*
	 * 管理sockt的数据 
	 * */
	this.socketDic = {};
	
	/*
	 * 离线消息缓存
	 * */
	this.chatCache = {};
	
	var client = new pg.Client(constring); //数据库操作对象
	client.connect(); //连接数据库
	var userTableName = 'HXUserTable';
	//创建用户数据库表
	this.initUserTable = function() {
		client.query('CREATE TABLE IF NOT EXISTS ' + userTableName + ' (_id serial NOT NULL, user_id serial primary key, ' +
			'name varchar(10), passwoed varchar(30),' +
			'friends int[], ' +
			'token char(32))');
	}
	this.initUserTable();
	//			client.end();//关闭数据库连接
	/*
	 * 创建用户数据
	 * */
	this.signup = function(name, passwoed) {
		console.log('创建好的表')
		client.query("insert into " + userTableName + " (name, passwoed, friends) values('" + name + "', '" + passwoed + "', '{}')");
	}

	/*
	 * 用户登陆
	 * */
	this.login = function(name, callback) {
		var query = client.query("select _id, name, token, passwoed from " + userTableName + " where name = '" + name + "'")
		query.on('row', function(row) {
			callback && callback(row);

			callback = null;
		});

	}

	/*
	 * 用户登陆
	 * */
	this.search_user = function(name, callback) {
		console.log('登陆' + name); //  like '%" + name + "%'"
		var query = client.query("select _id, name from " + userTableName + " where name like '%" + name + "%'")
		console.log('我是测试点1')
		var dataArray = [];
		query.on('row', function(row) {
			dataArray.push(row);
		});
		query.on('end', function() {
			callback && callback(dataArray);
		});
	}
	
	/*
	 * 更新token
	 * */
	this.setToken = function(_id,token, callback) {
		var query = client.query("update " + userTableName + " set token = '" + token +"' where _id = " + parseInt(_id))
//		console.log('我是测试点1')
//		var dataArray = [];
//		query.on('row', function(row) {
//			dataArray.push(row);
//		});
		query.on('end', function() {
			callback && callback();
		});
	}
	
	

	/*
	 * 添加好友关系
	 * 
	 * */
	this.setFriends = function(user_id_1, user_id_2, callback) {
		//		user_id_1 = 7;
		//		var sql = "insert into " + userTableName + " (friends) values()";
		//		var sql = " select  " + userTableName + " array_append(friends,5) where _id = '" + user_id_1+ "'";
		//		var sql = "update " + userTableName + " set friends = friends||302 where _id = '" + user_id_1+ "'";
		//		var sql = "update " + userTableName + " set friends = array_append(friends, " + user_id_2 + ") where _id = " + user_id_1+ "";
		//		var sql = "update " + userTableName + " set friends = friends||302 where _id = '" + parseInt(user_id_1) + "'";
		//		var sql = "select * from " + userTableName + " where _id = 7";
		console.log('user_id_1---' + user_id_1)
		console.log('user_id_2---' + user_id_2)
		var query1 = client.query("update " + userTableName + " set friends = array_append(friends, " + parseInt(user_id_2) + ") where _id = " + parseInt(user_id_1));
		var query2 = client.query("update " + userTableName + " set friends = array_append(friends, " + parseInt(user_id_1) + ") where _id = " + parseInt(user_id_2));
		//		var ind = 0
		//		query1.on('end', function() {
		//			
		//		});
		//		query2.on('end', function() {
		//			
		//		});
		callback && callback()
	}

	/*
	 * 获取好友列表
	 * */
	this.getFriendsList = function(user_id, callback) {
		console.log("获取好友列表" + user_id);
		var sql = "select friends from " + userTableName + " where _id = " + user_id;
		client.query(sql, function(error, results) {
			if(error) {
				return console.error('error running query--', error);
			}
			var rows = results.rows
			var len = rows.length,i;
			for(i = 0; i < len; i++) {
				console.log("多少消息" + JSON.stringify(rows[i].friends))
			}
			var friendsArray = rows[0].friends;
			var sql = "select * from " + userTableName + " where" // or _id = " + friendsStr;
			for (var i = 0; i < friendsArray.length; i++) {
				if (i == 0) {
					sql = sql + ' _id = ' + friendsArray[i]
				} else{
					sql = sql + ' or _id = ' + friendsArray[i]
				}
				
			}
			client.query(sql, function(error, results) {
				if(error) {
					return console.error('error running query--', error);
				}
				var len = results.rows.length,i;
//				for(i = 0; i < len; i++) {
//					var itme = results.rows[i]
//					console.log("多少消息---" + JSON.stringify(itme))
//				}
				callback && callback(results.rows)
			})

		})

	}

	this.all = function() {
		console.log("update beginning");
		var sql = "select * from " + userTableName;
		var query = client.query(sql);

		query.on('row', function(row) {
			console.log(JSON.stringify(row))
		});
	}

	this.all();

	//删除表  删除表中的所有行，而不记录单个行删除操作。  参数 userTableName 是要截断的表的名称或要删除其全部行的表的名称
	this.truncate = function() {
		var sql = "TRUNCATE TABLE " + userTableName;
		var query = client.query(sql);
		query.on('row', function(row) {
			console.log(JSON.stringify(row))
		});
	}
	//	this.truncate();
	//删除表
	this.truncate = function() {
		var sql = "Delete from " + userTableName + " where 1=1";
		var query = client.query(sql);
		query.on('row', function(row) {
			console.log(JSON.stringify(row))
		});
	}
	//
	this.DROP = function() {
		var sql = "DROP TABLE " + userTableName;
		var query = client.query(sql);
		query.on('row', function(row) {
			console.log(JSON.stringify(row))
		});
	}
//		this.DROP();

}



